import types from '../types'
import common from '../common'
import store from '../index.js'
import axios from 'axios'
import moment from 'moment'
import env from '@/config/env'
import {apiGetSign, apiUserLogin, apiModLoginPwd} from '@/service/apiService'
import {custsign, custsign2, createSignData} from '@/myutl/utlenc'
import {getStore, setStore} from '@/config/mUtils'

const state = {
  storeUser: {
    id: null,
    loginPwd: null,
    openId: null,
    name: null,
    avatar: null,
    isLoginSucc: false,
    errmsg: null,
    errdesc: null
  }
}

const getters = {
  storeUser(state) {
    return state.storeUser;
  }
}

const actions = {
  getUser({commit,state}, loginName) {
    axios.get('/api/user'+loginName).then(resp => {
      if(resp.data.errno == 0) {
        commit(types.GET_USER, resp.data.data);
      }
    });
  },
  async login({commit,state}, loginInfo) {
    let curTs = moment().format('YYYYMMDDHHmmss');
    let params = {
      "appId": env.appId,
      "charset": "utf-8",
      "timestamp": curTs,
      "version": "1.0",
      "appAuthToken": store.getters.authToken,
      "bizContent": {
        "verifyCode":"",
        "loginName": loginInfo.loginName,
        "type": "1",      // 1=手机
        "ip":"",
        "logSource":"test-app",
        "loginPassword": loginInfo.passWord,
        "terminalType":""
      }
    };
    let signData = createSignData(params);
    // console.log("createSignData:", signData);
    let retData = await apiGetSign(signData);
    if (retData.errno != 0) {
      commit(types.LOGIN_USER, {isLoginSucc: false, errmsg: "登录超时请重试", errdesc: "apiGetSign"});
      return;
    }
    params.signType = env.signType;
    params.sign = retData.sign;
    console.log("params:", params);

    retData = await apiUserLogin(params);
    console.log("retData:", retData);
    if (retData.subCode === undefined  || retData.subCode === null) {
      commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:retData.msg});
    } else {
      if (retData.subCode !== env.ERRCD_SUCC) {
        commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:retData.subMsg});
      } else {
        retData = retData.data;
        // console.log("retData:", retData);
        let userInfo = {
          "loginName": retData.loginName,
          "loginPwd": loginInfo.passWord,
          "appId": retData.appId,
          "openId": retData.openId,
          "name": retData.name ? retData.name : retData.loginName,
          "isUpdatedPwd": retData.isUpdatedPwd
        };
        commit(types.LOGIN_USER, {isLoginSucc:true, user:userInfo});
      }
    }
  },
  async modLoginPwd({commit, state}, pwdInfo) {
    console.log(state.user);
    let curTs = moment().format('YYYYMMDDHHmmss');
    let params = {
                  "appId": appId,
                  "charset": "utf-8",
                  "timestamp": curTs,
                  "version": "1.0",
                  "appAuthToken": store.getters.authToken,
                  "bizContent": {
                    "openId": state.user.openId,
                    "oldPassword": pwdInfo.encOldPwd,
                    "newPassword": pwdInfo.encNewPwd,
                  }
                };
    let signData = createSignData(params);
    console.log("createSignData:", signData);
    let retData = await apiGetSign(signData);
    if (retData.errno != 0) {
      commit(types.ACTION_RET, {isRetSucc: false, errmsg: "系统超时请重试"});
      return;
    }
    params.signType = "RSA2";
    params.sign = retData.sign;
    console.log("params:", params);
    retData = await apiModLoginPwd(params);
    if (retData.subCode === undefined  || retData.subCode === null) {
      commit(types.ACTION_RET, {isRetSucc:false, errmsg:retData.msg});
    } else {
      if (retData.subCode !== "0000") {
        commit(types.ACTION_RET, {isRetSucc:false, errmsg:retData.subMsg});
      } else {
        commit(types.ACTION_RET, {isRetSucc:true, errmsg: "密码修改成功"});
      }
    }
  },
  verifyCodeLogin({commit,state}, loginInfo) {
    // 异步操作前初始化
    console.log("isLocDev:", );
    store.dispatch('initAction');
    if (store.getters.isLocDev) {
      // TODO
    } else {
      let uri = "/hr/user/userloginwithregister.do";
      axios.get(uri,
                {
                  params:{
                    "appId": appId,
                    "charset": "utf-8",
                    "signType": "RSA2",
                    "timestamp": "20180315145053",
                    "version": "1.0",
                    "sign": "bn3nwBRjKs+sjfJy4IzyhfDg71xAlaljkZd80E2spyiOVsYadf8R33Qk6X7FPRDa1VnkotSWY2RJlBNoVYksv/U2gdw94AeQkLeXVIoOPO6AxrzlFoIHqxonmDVoGzqSFsMjabTAUhTOxXl4YNQIdSdaVKPGssSyAV88Ciuf4AU=",
                    "bizContent": {
                      "loginName": loginInfo.loginName,
                      "type": "1",      // 1=手机
                      "verifyCode": loginInfo.verifyCode,
                      "ip":"",
                      "logSource":"test-app",
                      "loginPassword": "",
                      "terminalType":""
                    }
                  }
                }, {timeout: 100}).then(resp => {
        console.log(uri, "get.params:", resp.config.params);
        console.log(uri, resp.data);
        if (resp.data.subCode === undefined  || resp.data.subCode === null) {
          commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:resp.data.msg});
        } else {
          if (resp.data.subCode !== "0000") {
            commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:resp.data.subMsg});
          } else {
            let userInfo = {
              "loginName": resp.data.loginName,
              "appId": resp.data.appId,
              "openId": resp.data.openId,
              "name": resp.data.name ? resp.data.name : resp.data.loginName,
              "isUpdatedPwd": resp.data.isUpdatedPwd
            };
            commit(types.LOGIN_USER, {isLoginSucc:true, user:userInfo});
          }
        }
      });
    }
  },
  sendMobileCode({commit,state}, smsInfo) {
    let uri = "/user/userservice/sendsms.do";
    console.log("sendMobileCode:", smsInfo);
    store.dispatch('initAction');
    axios.get(uri,
              {
                params:{
                  "appId": appId,
                  "charset": "utf-8",
                  "signType": "RSA2",
                  "timestamp": "20180315145053",
                  "version": "1.0",
                  "sign": "bn3nwBRjKs+sjfJy4IzyhfDg71xAlaljkZd80E2spyiOVsYadf8R33Qk6X7FPRDa1VnkotSWY2RJlBNoVYksv/U2gdw94AeQkLeXVIoOPO6AxrzlFoIHqxonmDVoGzqSFsMjabTAUhTOxXl4YNQIdSdaVKPGssSyAV88Ciuf4AU=",
                  "bizContent": {
                    "templateNo": smsInfo.templateNo,
                    "mobileNo": smsInfo.mobileNo
                  }
                }
              }, {timeout: 100}).then(resp => {
      console.log(uri, "get.params:", resp.config.params);
      console.log(uri, " then:", resp.data);
      if (resp.data.subCode === undefined  || resp.data.subCode === null) {
        commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:resp.data.msg});
      } else {
        if (resp.data.subCode !== "0000") {
          commit(types.LOGIN_USER, {isLoginSucc:false, errmsg:resp.data.subMsg});
        } else {
          // console.log(resp.data);
          commit(types.LOGIN_USER, {isLoginSucc:true});
        }
      }
    });
  }
}

const mutations = {
  [types.GET_USER](state,data){
    state.user = data;
    state.isUserExist = true;
    console.log("types.GET_USER:", data);
  },
  [types.LOGIN_USER](state, data) {
    if (data.isLoginSucc) {
      state.storeUser.id = data.user.loginName;
      state.storeUser.loginPwd = data.user.loginPwd;
      state.storeUser.openId = data.user.openId;
      state.storeUser.name = data.user.name;
      // state.storeUser.avatar = data.user.;
      state.storeUser.isLoginSucc = true;
      // console.log("data.user:", data.user);
      // console.log("state.storeUser:", state.storeUser);
      setStore('storeUser', state.storeUser);
    } else {
      state.storeUser.isLoginSucc = false;
      state.storeUser.errmsg = data.errmsg;
      if (data.errdesc) {
        state.storeUser.errdesc = data.errdesc;
      }
    }
  },
}

export default {
  state,
  getters,
  actions,
  mutations
}
